package treenode;

import treenode.BinaryTree;

public class MyTree<E> implements BinaryTree<E> {
    private TreeNode<E> root;

    public MyTree(TreeNode<E> root) {
        this.root = root;
    }

    public TreeNode<E> getRoot() {
        return root;
    }

    public void setRoot(TreeNode<E> root) {
        this.root = root;
    }

    @Override
    public void insertL(TreeNode<E> node, E var) {
        if (node.left != null) {
            throw new RuntimeException("左子树已存在，不能添加");
        }
        TreeNode<E> newNode = new TreeNode<>(var);
        node.left = newNode;
    }

    @Override
    public void insertR(TreeNode<E> node, E var) {
        if (node.right != null) {
            throw new RuntimeException("右子树已存在，不能添加");
        }
        TreeNode<E> newNode = new TreeNode<>(var);
        node.right = newNode;
    }

    @Override
    public TreeNode<E> getLChild(TreeNode<E> node) {
        return node.left;
    }

    @Override
    public TreeNode<E> getRChild(TreeNode<E> node) {
        return node.right;
    }

    public void preOrder(TreeNode node) {
        if (node != null) {

            // 根
            System.out.println(node.date);
            // 左
            preOrder(node.left);
            // 右
            preOrder(node.right);
        }
    }

    public void midOrder(TreeNode node) {
        if (node != null) {

            // 左
            midOrder(node.left);
            // 根
            System.out.println(node.date);
            // 右
            midOrder(node.right);
        }
    }

    public void afterOrder(TreeNode node) {
        if (node != null) {

            // 左
            afterOrder(node.left);
            // 右
            afterOrder(node.right);
            // 根
            System.out.println(node.date);
        }
    }

    public void traversal(int type) {
        switch (type) {
            case 1:
                preOrder(root);
                break;
            case 2:
                midOrder(root);
                break;
            case 3:
                afterOrder(root);
                break;
        }
    }
}
